package com.zhxymm.book.controllers;

import com.zhxymm.book.dao.UserAccountRepository;
import com.zhxymm.book.entity.UserAccount;
import com.zhxymm.book.service.UserAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("userAccounts")
public class UserAccountController {
    @Autowired
    UserAccountService userAccountService;
    @GetMapping
    public String displayUserAccounts(Model model){
        List<UserAccount> userAccounts = userAccountService.getAll();
        model.addAttribute("userAccounts",userAccounts);
        return "userAccounts/list-userAccounts";
    }
    @GetMapping("/new")
    public String displayUserAccountForm(Model model){
        UserAccount aUserAccount = new UserAccount();
        model.addAttribute("userAccount",aUserAccount);
        return "userAccounts/new-userAccount";
    }
    @PostMapping("/save")
    public String createUserAccount(Model model,UserAccount userAccount){
        userAccountService.save(userAccount);
        return "redirect:/userAccounts";
    }
    @GetMapping("/update")
    public String displayUserAccountUpdateForm(@RequestParam("id") long theId,Model model){
        UserAccount theUserAccount = userAccountService.findByUserAccount(theId);
        model.addAttribute("userAccount",theUserAccount);
        return "userAccounts/new-userAccount";
    }
    @GetMapping("/delete")
    public String deleteUserAccount(@RequestParam("id") long theId,Model model){
        UserAccount theUserAccount = userAccountService.findByUserAccountId(theId);
        userAccountService.delete(theUserAccount);
        return "redirect:/userAccounts/new";
    }
}
